package com.deng.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.deng.common.lang.Consts;
import com.deng.common.lang.Result;
import com.deng.entity.Post;
import com.deng.entity.User;
import com.deng.entity.Usermessage;
import com.deng.shiro.AccountProfile;
import com.deng.util.UploadUtil;
import com.deng.vo.UserMessageVo;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.deng.controller.BaseController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Date;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dengwenxiong
 * @since 2021-05-05
 */
@Controller
public class UserController extends BaseController {
    @Autowired
    UploadUtil uploadUtil;
    @RequestMapping("/user/home")
    public String home(){
        User user=userService.getById(getProfileId());
        //获取该用户最近发表的文章
        List<Post> posts=postService.list(new QueryWrapper<Post>().eq("user_id",getProfileId()).gt("created", DateUtil.offsetDay(new Date(),30)).orderByDesc("created"));
        req.setAttribute("user",user);
        req.setAttribute("posts",posts);
        return "/user/home";
    }
    @GetMapping("/user/set")
    public String set(){
        User user=userService.getById(getProfileId());
        req.setAttribute("user",user);
        return "/user/set";
    }
    @PostMapping("/user/set")
    @ResponseBody
    public Result doSet(User user){
        if(StrUtil.isNotBlank(user.getAvatar())){
            User temp =userService.getById(getProfileId());
            temp.setAvatar(user.getAvatar());
            userService.updateById(temp);
            //更新shiro
            AccountProfile profile=getProfile();
            profile.setAvatar(user.getAvatar());
            //修改session
            SecurityUtils.getSubject().getSession().setAttribute("profile",profile);
            return Result.success().action("/user/set#avatar");
        }
       if(StrUtil.isBlank(user.getUsername())){
           return Result.fail("昵称不能为空");
        }
        //用户名不重复
        int count=userService.count(new QueryWrapper<User>().eq("username",user.getUsername()).ne("id",getProfileId()));
        if(count!=0){
           return Result.fail("用户名已经被占用");
        }
        User temp=userService.getById(getProfileId());
        temp.setSign(user.getSign());
        temp.setUsername(user.getUsername());
        temp.setGender(user.getGender());
        temp.setSign(user.getSign());
        userService.updateById(temp);
        //修改shiro的用户缓存
        AccountProfile profile=getProfile();
        profile.setSign(temp.getSign());
        profile.setUsername(temp.getUsername());
        //修改session
        SecurityUtils.getSubject().getSession().setAttribute("profile",profile);
        return Result.success().action("/user/set#info");
    }
    //重设密码
    @ResponseBody
    @PostMapping("/user/repass")
    public Result repass(String nowpass, String pass, String repass) {
        System.out.println("正在重设密码");
        if(!pass.equals(repass)) {
            return Result.fail("两次密码不相同");
        }

        User user = userService.getById(getProfileId());

        String nowPassMd5 = SecureUtil.md5(nowpass);
        if(!nowPassMd5.equals(user.getPassword())) {
            return Result.fail("密码不正确");
        }

        user.setPassword(SecureUtil.md5(pass));
        userService.updateById(user);
        return Result.success().action("/user/set#pass");

    }
    //上传头像
    @PostMapping("/user/upload")
    @ResponseBody
    public Result upload(@RequestParam(value = "file") MultipartFile file) throws IOException {
        return uploadUtil.upload(UploadUtil.type_avatar,file);
    }
    //用户中心
    @GetMapping("/user/index")
    public String index(){
        return "/user/index";
    }
    //我的消息
    //发表的文章
    @ResponseBody
    @GetMapping("/user/publish")
    public Result publish(){
        IPage page=postService.page(getPage(),new QueryWrapper<Post>().eq("user_id",getProfileId()).orderByDesc("created"));
        return Result.success(page);
    }
    //收藏的文章
    @ResponseBody
    @GetMapping("/user/collection")
    public Result collection(){
        IPage page=postService.page(getPage(),new QueryWrapper<Post>().inSql("id","select post_id from usercollection where user_id ="+getProfileId()));
        return Result.success(page);
    }
    @GetMapping("/user/mess")
    public String mess(){
        IPage<UserMessageVo> page=usermessageService.paging(getPage(),new QueryWrapper<Usermessage>().eq("to_user_id",getProfileId()).orderByDesc("created"));
        //查看后消息状态改变
        List<Long> ids=new ArrayList<>();
        for(UserMessageVo userMessageVo:page.getRecords()){
            if(userMessageVo.getStatus()==0){
                ids.add(userMessageVo.getId());
            }
        }
        usermessageService.updateToReader(ids);
        req.setAttribute("pageData",page);
        return "/user/mess";
    }
    //消息删除与清除全部消息
    @ResponseBody
    @PostMapping("/message/remove")
    public Result messageremove(Long id,@RequestParam(defaultValue = "false") Boolean all){
        //当all为true表示删除全部，此时不加当前消息id，当all为false表示删除单条消息，此时加上消息id
        boolean remove=usermessageService.remove(new QueryWrapper<Usermessage>().eq("to_user_id",getProfileId()).eq(!all,"id",id));
        return remove ? Result.success() : Result.fail("删除失败");
    }

    //登录后发起一个请求/messgae/nums，获取当前用户的未读消息
    @ResponseBody
    @RequestMapping("/message/nums/")
    public Map msgNums() {

        int count = usermessageService.count(new QueryWrapper<Usermessage>()
                .eq("to_user_id", getProfileId())
                .eq("status", "0")
        );
        return MapUtil.builder("status", 0).put("count", count).build();
    }

}
